<template>
  <div>
    <h1 style="text-align: center;color: red">购物车信息</h1>
    <table style="margin-top: 20px">
      <tr>
        <td>商品编号：</td>
        <td><input type="text" v-model.number="book.id"></td>
      </tr>
      <tr>
        <td>商品标题：</td>
        <td><input type="text" v-model.number="book.title"></td>
      </tr>
      <tr>
        <td>商品价格：</td>
        <td><input type="text" v-model.number="book.price"></td>
      </tr>
      <tr>
        <td>商品数量：</td>
        <td><input type="text" v-model.number="book.count"></td>
      </tr>
      <tr>
        <td colspan="2">
          <button @click="addCarts(book)">添加购物车</button>
        </td>
      </tr>
    </table>
    <hr>
    <table>
      <thead>
      <tr>
        <th>编号</th>
        <th>商品名称</th>
        <th>单价</th>
        <th>数量</th>
        <th>金额</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(book,index) in books" :key="book.id">
        <td>{{ book.id }}</td>
        <td>{{ book.title }}</td>
        <td>{{ book.price }}</td>
        <td>
          <button style="width:12%" @click="add(index)">+</button>
          {{ book.count }}
          <button style="width:12%" @click="minus(index)">-</button>
        </td>
        <td>{{ book.count * book.price }}</td>
        <td>
          <button @click="delCarts(index)">删除</button>
        </td>
      </tr>
      </tbody>
    </table>
    <div>总价：{{ totalPrice }}</div>
  </div>
</template>

<script>

import {mapMutations, mapState, mapGetters,mapActions} from "vuex"

export default {
  name: "index",
  data() {
    return {
      book: {
        id: "",
        title: "",
        price: "",
        count: 1
      }
    }
  },

  // 4、解构写法
  computed: {
    ...mapState('carts',{books: "items"}),
    // // 1、原始写法
    // totalPrice(){
    //   return this.$store.getters.totalPrice;
    // }

    // 2、数组写法 监听公共的计算属性
    ...mapGetters('carts',["totalPrice"]),
  },

  // 4、解构写法
  methods: {
    ...mapMutations('carts',{add: "addBookCount",minus:"lessBookCount",delCarts: "delShopCarts"}),

    ...mapActions('carts',['addCarts'])
    // addCarts() {
    //   this.$store.dispatch("addCarts", this.book);
    // }
  }

}
</script>

<style scoped>
.pug-ui-content table {
  width: 100%;
  border-collapse: collapse;
}

.pug-ui-content tr th, .pug-ui-content tr td {
  border: 1px solid #ccc;
  padding: 8px;
}
</style>